package top.tupobi.zing.network;

import android.os.Build;
import android.util.Log;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import top.tupobi.zing.InfoRecord;
import top.tupobi.zing.utils.MD5Utils;

public class NetInterceptor {

    private static Interceptor sHeaderInterceptor = new Interceptor() {

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public Response intercept(@Nullable Chain chain) throws IOException {
            String timestamp = String.valueOf(new Date().getTime());
            String username = InfoRecord.getUsername();
            String id = InfoRecord.getUserId();

            Request request = Objects.requireNonNull(chain).request()
                    .newBuilder()
                    .addHeader("id", id)
                    .addHeader("timestamp", timestamp)
                    .addHeader("username", username)
                    .addHeader("token", MD5Utils.md5(id + timestamp + username))
                    .build();
            return chain.proceed(request);
        }
    };

    public static Interceptor getHeaderInterceptor() {
        return sHeaderInterceptor;
    }

    private static HttpLoggingInterceptor sLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(@Nullable String message) {
            Log.e("LoggingInterceptor", "Json数据：" + message);
        }
    }).setLevel(HttpLoggingInterceptor.Level.BODY);

    public static HttpLoggingInterceptor getLoggingInterceptor() {
        return sLoggingInterceptor;
    }

}
